package com.example.graduatedesigned;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.graduatedesigned.activity.HistoryCharts;
import com.example.graduatedesigned.adapter.MainAdapter;
import com.example.graduatedesigned.bean.DataResponse;
import com.example.graduatedesigned.bean.DeviceItem;
import com.example.graduatedesigned.bean.DeviceStatus;
import com.example.graduatedesigned.bean.ItemBean;
import com.example.graduatedesigned.bean.ProductRequest;
import com.example.graduatedesigned.http.ApiService;
import com.example.graduatedesigned.http.RetrofitClient;
import com.example.graduatedesigned.utils.DevicesInfo;
import com.example.graduatedesigned.utils.DisplayUtils;
import com.example.graduatedesigned.utils.MainItemDecoration;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mainRv;
    private List<ItemBean> dataList;
    private MainAdapter myAdapter;
    private final Timer timer = new Timer();
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            initData();
        }
    };
    Observable<DataResponse<List<DeviceItem>>> observable2;
    Observable<DataResponse<DeviceStatus>> observable1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initHttp();
    }

    private void setDeviceStatus(boolean checked) {
        ApiService service = RetrofitClient.getInstance();
        String productId = DevicesInfo.product_id;
        String deviceName = DevicesInfo.device_name;
        ProductRequest.Params params = new ProductRequest.Params(checked);
        ProductRequest productRequest = new ProductRequest(productId, deviceName, params);
        Call<DataResponse> call = service.setDeviceStatus(DevicesInfo.auth_info, productRequest);
        call.enqueue(new Callback<DataResponse>() {
            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
                DataResponse body = response.body();
                if (body.getData() == null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Log.d("joidajodas", t.toString());
            }
        });
    }

    private void initView() {
        mainRv = findViewById(R.id.mainRv);
        mainRv.setLayoutManager(new GridLayoutManager(this,2));
        //初始化数据
        dataList = new ArrayList<>();
        //初始化适配器
        myAdapter = new MainAdapter(this);
        myAdapter.setNewInstance(dataList);
        int space = DisplayUtils.dp2px(10f);
        mainRv.addItemDecoration(new MainItemDecoration(space));
        mainRv.setPadding(space,0,0,0);
        mainRv.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (position != 3) {
                    Intent intent = new Intent(MainActivity.this, HistoryCharts.class);
                    String option = position == 1 ? "temp" : "humi";
                    intent.putExtra("selected", option);
                    startActivity(intent);
                }
            }
        });
        myAdapter.addChildClickViewIds(R.id.mainSwitch);
        myAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (view instanceof SwitchCompat) {
                    setDeviceStatus(((SwitchCompat) view).isChecked());
                }
            }
        });
    }

    public void initHttp() {
        ApiService service = RetrofitClient.getInstance();
        String productId = DevicesInfo.product_id;
        String deviceName = DevicesInfo.device_name;
        String info = DevicesInfo.auth_info;
        long endTime = System.currentTimeMillis();
        long startTime = endTime - 7 * 24 * 60 * 60 * 1000;
        observable1 = service.getDeviceStatus(productId, deviceName, info, startTime, endTime, 1);
        observable2 = service.getDeviceInfo(productId, deviceName, info);
        timer.schedule(timerTask, 0, 3000);
    }

    private void initData() {
        observable1.subscribeOn(Schedulers.io())               // （初始被观察者）切换到IO线程进行网络请求1
                .observeOn(AndroidSchedulers.mainThread())  // （新观察者）切换到主线程 处理网络请求1的结果
                .doOnNext(new Consumer<DataResponse<DeviceStatus>>() {
                    @Override
                    public void accept(DataResponse<DeviceStatus> response) throws Exception {
                        DeviceStatus deviceStatus = response.getData();
                        if (deviceStatus == null) return;
                        dataList.clear();
                        List<DeviceStatus.Status> data = deviceStatus.getList();
                        DeviceStatus.Status status = data.get(0);
                        String onlineStatus = (status.getStatus() == 0) ? "离线" : "在线";
                        dataList.add(0, new ItemBean("设备状态", onlineStatus, R.drawable.devices_status, "0", false));
                    }
                })
                .observeOn(Schedulers.io())
                .flatMap(new Function<DataResponse<DeviceStatus>, ObservableSource<DataResponse<List<DeviceItem>>>>() {
                    @Override
                    public ObservableSource<DataResponse<List<DeviceItem>>> apply(DataResponse<DeviceStatus> deviceStatusDataResponse) throws Exception {
                        return observable2;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataResponse<List<DeviceItem>>>() {
                    @Override
                    public void accept(DataResponse<List<DeviceItem>> response) throws Exception {
                        List<DeviceItem> data = response.getData();
                        if (data == null) return;
                        DeviceItem wet = data.get(0);
                        DeviceItem humidifier = data.get(1);
                        DeviceItem temp = data.get(3);
                        dataList.add(new ItemBean("温度", temp.getValue(), R.drawable.tempreature, "0", false));
                        dataList.add(new ItemBean("湿度", wet.getValue(), R.drawable.humidity, "0", false));
                        dataList.add(new ItemBean("加湿器", "", R.drawable.wet_machine, "1", humidifier.getValue().equals("true")));
                        myAdapter.setNewInstance(dataList);
                        myAdapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        System.out.println("登录失败");
                    }
                });
    }
}